<template>
  <div class="student-container">
    <el-container>
      <el-header>
        <div class="header-content">
          <h2>学生选课中心</h2>
          <div class="header-actions">
            <span>欢迎，{{ authStore.user?.name }}</span>
            <el-button type="danger" size="small" @click="handleLogout">
              退出登录
            </el-button>
          </div>
        </div>
      </el-header>
      
      <el-main>
        <el-tabs v-model="activeTab">
          <el-tab-pane label="可选课程" name="available">
            <el-card>
              <el-table :data="availableCourses" style="width: 100%">
                <el-table-column prop="title" label="课程名称" width="180" />
                <el-table-column prop="description" label="课程描述" />
                <el-table-column prop="teacher" label="授课教师" width="120" />
                <el-table-column label="容量/已选" width="100">
                  <template #default="{ row }">
                    <span>{{ row.enrolled }}/{{ row.capacity }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="schedule" label="上课时间" width="150" />
                <el-table-column prop="location" label="上课地点" width="120" />
                <el-table-column label="操作" width="100">
                  <template #default="{ row }">
                    <el-button
                      type="primary"
                      size="small"
                      :disabled="isEnrolled(row.id) || row.status === 'full'"
                      @click="enrollCourse(row)"
                    >
                      {{ isEnrolled(row.id) ? '已选' : '选课' }}
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-tab-pane>
          
          <el-tab-pane label="我的课程" name="enrolled">
            <el-card>
              <el-table :data="enrolledCourses" style="width: 100%">
                <el-table-column prop="title" label="课程名称" width="180" />
                <el-table-column prop="description" label="课程描述" />
                <el-table-column prop="teacher" label="授课教师" width="120" />
                <el-table-column prop="schedule" label="上课时间" width="150" />
                <el-table-column prop="location" label="上课地点" width="120" />
                <el-table-column label="操作" width="100">
                  <template #default="{ row }">
                    <el-button
                      type="danger"
                      size="small"
                      @click="dropCourse(row)"
                    >
                      退课
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { useCoursesStore } from '@/stores/courses'
import { useUsersStore } from '@/stores/users'

const router = useRouter()
const authStore = useAuthStore()
const coursesStore = useCoursesStore()
const usersStore = useUsersStore()

const activeTab = ref('available')

// 可选课程（未选且未满员的课程）
const availableCourses = computed(() => {
  return coursesStore.getAvailableCourses().filter(course => 
    !isEnrolled(course.id)
  )
})

// 已选课程
const enrolledCourses = computed(() => {
  const enrolledIds = usersStore.getUserEnrolledCourses(authStore.user.id)
  return coursesStore.courses.filter(course => enrolledIds.includes(course.id))
})

// 检查是否已选某课程
const isEnrolled = (courseId) => {
  const enrolledIds = usersStore.getUserEnrolledCourses(authStore.user.id)
  return enrolledIds.includes(courseId)
}

const handleLogout = () => {
  authStore.logout()
  router.push('/login')
}

// 选课
const enrollCourse = async (course) => {
  try {
    await ElMessageBox.confirm(
      `确定要选课程 "${course.title}" 吗？`,
      '选课确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // 先更新课程选课人数
    const courseSuccess = coursesStore.enrollStudent(course.id, authStore.user.id)
    if (courseSuccess) {
      // 再更新用户选课记录
      const userSuccess = usersStore.enrollCourse(authStore.user.id, course.id)
      if (userSuccess) {
        ElMessage.success('选课成功！')
      } else {
        // 如果用户选课失败，回滚课程选课人数
        coursesStore.updateCourse(course.id, { enrolled: course.enrolled })
        ElMessage.error('选课失败，请重试！')
      }
    } else {
      ElMessage.error('课程已满员，选课失败！')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('选课操作失败！')
    }
  }
}

// 退课
const dropCourse = async (course) => {
  try {
    await ElMessageBox.confirm(
      `确定要退选课程 "${course.title}" 吗？`,
      '退课确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const success = usersStore.dropCourse(authStore.user.id, course.id)
    if (success) {
      ElMessage.success('退课成功！')
    } else {
      ElMessage.error('退课失败，请重试！')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('退课操作失败！')
    }
  }
}

onMounted(() => {
  coursesStore.initializeCourses()
  usersStore.initializeUsers()
})
</script>

<style scoped>
.student-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
  background-attachment: fixed;
  padding: 20px;
}

.el-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  margin-bottom: 20px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  height: 70px;
}

.header-content h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
  background: linear-gradient(45deg, #00b894, #00cec9);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-actions span {
  color: #7f8c8d;
  font-weight: 500;
}

.el-main {
  padding: 0;
}

.el-tabs {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
  transition: all 0.3s ease;
}

.el-tabs:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

:deep(.el-tabs__header) {
  background: linear-gradient(45deg, #f8f9fa, #e9ecef);
  margin: 0;
  padding: 0 20px;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
  background-color: rgba(0, 0, 0, 0.05);
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
  padding: 0 24px;
  height: 60px;
  line-height: 60px;
  color: #7f8c8d;
  transition: all 0.3s ease;
}

:deep(.el-tabs__item:hover) {
  color: #00b894;
}

:deep(.el-tabs__item.is-active) {
  color: #00b894;
  font-weight: 600;
}

:deep(.el-tabs__active-bar) {
  background-color: #00b894;
  height: 3px;
}

:deep(.el-tabs__content) {
  padding: 24px;
}

.el-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.el-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

:deep(.el-card__header) {
  background: linear-gradient(45deg, #f8f9fa, #e9ecef);
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  padding: 16px 20px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header) {
  background: linear-gradient(45deg, #f8f9fa, #e9ecef);
}

:deep(.el-table th) {
  background: transparent;
  color: #2c3e50;
  font-weight: 600;
  border-bottom: 2px solid #dee2e6;
}

:deep(.el-table tr:hover) {
  background-color: rgba(116, 185, 255, 0.05);
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-button--primary) {
  background: linear-gradient(45deg, #00b894, #00cec9);
  border: none;
}

:deep(.el-button--danger) {
  background: linear-gradient(45deg, #e17055, #d63031);
  border: none;
}

:deep(.el-button--small) {
  padding: 8px 16px;
  font-size: 14px;
}

:deep(.el-button.is-disabled) {
  opacity: 0.6;
  cursor: not-allowed;
}

:deep(.el-message-box) {
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

:deep(.el-message-box__header) {
  background: linear-gradient(45deg, #f8f9fa, #e9ecef);
  border-radius: 16px 16px 0 0;
  padding: 20px 24px;
}
</style>